package openase.audiosearch.comm.request.encoder.factory;

import java.util.HashMap;
import java.util.Map;

import openase.audiosearch.comm.request.AudioRegistration;
import openase.audiosearch.comm.request.AudioSearch;
import openase.audiosearch.comm.request.Request;
import openase.audiosearch.comm.request.encoder.AudioRegistrationRequestEncoder;
import openase.audiosearch.comm.request.encoder.AudioSearchRequestEncoder;
import openase.audiosearch.comm.request.encoder.RequestEncoder;


public class RequestEncoderFactory {

	private static final Map<Class<? extends Request>, RequestEncoder<? extends Request>> ENCODERS;
	static {
		ENCODERS = new HashMap<Class<? extends Request>, RequestEncoder<? extends Request>>();
		ENCODERS.put(AudioRegistration.class, new AudioRegistrationRequestEncoder());
		ENCODERS.put(AudioSearch.class, new AudioSearchRequestEncoder());
	}

	private RequestEncoderFactory() {
	}

	@SuppressWarnings("unchecked")
	public static <T extends Request> RequestEncoder<T> getEncoder(T request) {
		if (request == null) {
			return null;
		}
		return (RequestEncoder<T>) get(request.getClass());
	}

	private static RequestEncoder<? extends Request> get(Class<?> clazz) {
		RequestEncoder<? extends Request> encoder = ENCODERS.get(clazz);
		if (encoder != null) {
			return encoder;
		}
		encoder = get(clazz.getSuperclass());
		if (encoder != null) {
			return encoder;
		}
		for (Class<?> itfce : clazz.getInterfaces()) {
			encoder = get(itfce);
			if (encoder != null) {
				return encoder;
			}
		}
		return null;
	}
}
